package com.linln.admin.pcs.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class TemplateMessageService {

    @Autowired
    private WxMpService wxMpService;

    public String sendTemplateMessage(String openId, String templateId, String page,
                                    Map<String, String> data) throws WxErrorException {
        String accessToken = wxMpService.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

        JSONObject json = new JSONObject();
        json.put("touser", openId);
        json.put("template_id", templateId);
        json.put("page", page);

        JSONObject dataJson = new JSONObject();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            JSONObject item = new JSONObject();
            item.put("value", entry.getValue());
            dataJson.put(entry.getKey(), item);
        }
        json.put("data", dataJson);

        String result = HttpUtil.post(url, json.toString());
        return result+"|"+accessToken;
    }
}
